<template>
  <div>
    
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>工人名字</th>
          <th>安全帽佩戴情况</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="worker in workers" :key="worker.id">
          <td>{{ worker.id }}</td>
          <td>{{ worker.name }}</td>
          <td>
            <el-tag :type="worker.state === '已佩戴' ? 'success' : 'danger'">
              {{ worker.state }}
            </el-tag>
          </td>
          <td>
            <button @click="toggleSafetyHelmet(worker)">切换状态</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'http://localhost:8090',
  headers: {
    'Content-Type': 'application/json'
  }
});

export default {
  data() {
    return {
      workers: []
    };
  },
  mounted() {
    this.fetchWorkers();
  },
  methods: {
    fetchWorkers() {
      apiClient.post('/attendance/get')
        .then(response => {
          const workers = response.data.map(worker => {
            worker.state = ''; // 初始化安全帽佩戴情况为空
            return worker;
          });
          this.workers = workers;
        })
        .catch(error => {
          console.error('Error fetching workers', error);
        });
    },
    toggleSafetyHelmet(worker) {
      const newSafetyState = worker.state === '已佩戴' ? '未佩戴' : '已佩戴';
      worker.state = newSafetyState; // 直接更新安全帽状态
    }
  }
};
</script>

<style>
  table {
    border-collapse: collapse;
    width: 100%;
  }

  th, td {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
  }

  th {
    background-color: #f2f2f2;
  }

  tr:nth-child(even) {
    background-color: #f2f2f2;
  }
</style>
